package com.woshua.hongbao.service;

import android.accessibilityservice.AccessibilityService;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.List;

public class HongBaoService extends AccessibilityService {

    private String[] filter=new String[]{"刷新"};

//    监听窗口毁掉
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

        //tree view--textview
        AccessibilityNodeInfo info = event.getSource();
        if (info==null)
        {
            return;
        }
        startClick(info);
    }

    private void startClick(AccessibilityNodeInfo info) {
        //通过findViewById
        List<AccessibilityNodeInfo> list = findByText(info);

        if(list==null)
        {
            return;
        }

        AccessibilityNodeInfo nodeInfo = list.get(list.size() - 1);

        //OnClick performClick
        boolean isChecked = nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);


        if(!isChecked)
        {
            //重复点击
            reClick(info);
        }
    }

    private void reClick(AccessibilityNodeInfo info) {
        int childCount = info.getChildCount();

        if(childCount==0)
        {
            info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }

        for (int i = 0; i < childCount; i++) {
            AccessibilityNodeInfo infoChild = info.getChild(i);

            if(infoChild==null)
            {
                continue;
            }

            if(infoChild.getChildCount()>0)
            {
                reClick(infoChild);
            }
            else
            {
                info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
        }
    }

    private List<AccessibilityNodeInfo> findByText(AccessibilityNodeInfo info) {
        for (String text : filter) {
            List<AccessibilityNodeInfo> list =
                    info.findAccessibilityNodeInfosByText(text);
            if(list!=null && !list.isEmpty())
            {
                return list;
            }
        }

        return null;
    }

    @Override
    public void onInterrupt() {

    }
}
